import React, {useState} from 'react';
import {View, Button, Text, TextInput} from 'react-native';
import {HelloWorldContract} from '../contracts/HelloWorld';
import {build_raw_tx} from '../utils/txhelper';
import '../utils/myglobal.js';
import mystyles from './mystyles';

import {bcos_raw, bcos_rpc} from '../utils/bcosproxy_util';
const DemoHelloWorld = () => {
  const [inputData, setInputData] = useState('new value');
  const [resultData, setResultData] = useState('waiting click...');
  const dofetch = function (mode) {
    console.log('mode = ', mode);
    fetchData(mode);
  };
  let helloworld = new HelloWorldContract();
  let contractname = 'HelloWorld';
  let address = '0xbe6e9bef148d9c3ac77f28c426e609ea7b7e437a';
  function doGet() {
    let get_raw_data = helloworld.create_get();
    bcos_raw('call', contractname, address, get_raw_data).then(result => {
      //console.log('get raw result  ', result);
      //let jsonResult = JSON.parse(result);
      if ('output_result' in result) {
        setResultData('GET链上数据结果: [' + result.output_result + ']');
      } else {
        console.error(result);
      }
    });
  }

  const fetchData = async mode => {
    try {
      console.log('global url', global.proxy_url);
      console.log('fetchData mode:', mode);

      let blocklimit = 0;

      if (mode == 'set') {
        const blocklimitresponse = await bcos_rpc('getBlocklimit'); // 替换为你的URL
        blocklimit = parseInt(blocklimitresponse);

        console.log('blocklimit ', blocklimit);
        let func_set = helloworld.create_set_data(inputData);
        let set_raw_data = build_raw_tx(blocklimit, address, func_set);
        bcos_raw('sendtx', contractname, address, set_raw_data).then(result => {
          if ('status' in result) {
            setResultData(
              'SET写入链上: [ ' + inputData + ' ], 结果 : ' + result.status,
            );
          } else {
            console.error(result);
          }
        });
      } else if (mode == 'get') {
        doGet();
      }
    } catch (error) {
      console.error(error);
      //console.stack(error)
      setResultData('操作失败: [ ' + error);
    }
  };

  return (
    <View style={{width: '100%', alignSelf: 'center'}}>
      <View style={{flexDirection: 'row'}}>
        <Text style={[mystyles.SubTitle, {paddingVertical: 1}]}>
          [{contractname}]:
        </Text>
        <Text style={[mystyles.text, {fontSize: 14, color: 'darkblue'}]}>
          {address}
        </Text>
      </View>
      <View style={{flexDirection: 'row'}}>
        <Text style={[mystyles.text]}>输入新的值 : </Text>

        <TextInput
          id="userinput"
          style={{
            flex: 1,
            height: 40,
            borderColor: 'darkblue',
            borderWidth: 1,
          }}
          onChangeText={v => {
            setInputData(v);
            //console.log('inputData is ' + v);
          }}
          defaultValue={inputData}
        />
      </View>
      <Text style={[mystyles.text, {color: '#33a8ff'}]}>{resultData}</Text>
      <View>
        <Button title="GET" onPress={() => fetchData('get')} />
        <View style={mystyles.separator} />
        <Button title="SET" onPress={() => fetchData('set')} />
      </View>
    </View>
  );
};

export default DemoHelloWorld;
